package com.wan.controller;

import com.wan.pojo.Page;
import com.wan.pojo.Role;
import com.wan.pojo.User;
import com.wan.service.LogService;
import com.wan.service.RoleService;
import com.wan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class UserController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private LogService logService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ModelAndView list(ModelAndView model){
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Role> roleList = roleService.getRoleList(map);
        model.addObject("roleList",roleList);
        model.setViewName("user/list");
        return model;
    }
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> findList(Page page,
        @RequestParam(name="username",required=false ,defaultValue="") String username,
        @RequestParam(name = "roleId",required = false ) Long roleId,
        @RequestParam(name = "sex",required = false) Integer sex
    ){
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset",page.getOffset());
        queryMap.put("pageSize",page.getRows());
        queryMap.put("username",username);
        queryMap.put("roleId",roleId);
        queryMap.put("sex",sex);
        map.put("rows", userService.findList(queryMap));
        map.put("total", userService.getTotal(queryMap));
        return map;
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> add(User user){
        Map<String, String> map = new HashMap<String, String>();
        if(user==null){
            map.put("type","error");
            map.put("msg","请填写用户信息！");
            return map;
        }
        if(StringUtils.isEmpty(user.getUsername())){
            map.put("type","error");
            map.put("msg","请填写用户名！");
            return map;
        }
        if(StringUtils.isEmpty(user.getPassword())){
            map.put("type","error");
            map.put("msg","请填写用户密码！");
            return map;
        }
        if(user.getRoleId() == null){
            map.put("type", "error");
            map.put("msg", "请选择所属角色！");
            return map;
        }
        if(isExist(user.getUsername(), 0l)){
            map.put("type", "error");
            map.put("msg", "该用户名已经存在，请重新输入！");
            return map;
        }
        if(userService.add(user)<=0){
            map.put("type", "error");
            map.put("msg", "添加失败，请联系管理员！");
            return map;
        }
        map.put("type", "success");
        map.put("msg", "添加成功！");
        return map;
    }
    //修改用户
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> edit(User user){
        Map<String, String> map = new HashMap<String, String>();
        if(user==null){
            map.put("type","error");
            map.put("msg","请填写用户信息！");
            return map;
        }
        if(StringUtils.isEmpty(user.getUsername())){
            map.put("type","error");
            map.put("msg","请填写用户名！");
            return map;
        }
        if(user.getRoleId() == null){
            map.put("type", "error");
            map.put("msg", "请选择所属角色！");
            return map;
        }
        if(isExist(user.getUsername(), user.getId())){
            map.put("type", "error");
            map.put("msg", "该用户名已经存在，请重新输入！");
            return map;
        }
        if(userService.edit(user)<=0){
            map.put("type", "error");
            map.put("msg", "修改失败，请联系管理员！");
            return map;
        }
        map.put("type", "success");
        map.put("msg", "修改成功！");
        return map;
    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @RequestMapping(value="/delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> delete(String ids){
        Map<String, String> map = new HashMap<String, String>();
        if(StringUtils.isEmpty(ids)){
            map.put("type", "error");
            map.put("msg", "选择要删除的数据！");
            return map;
        }
        if(ids.contains(",")){
            ids = ids.substring(0,ids.length()-1);
        }
        if(userService.delete(ids) <= 0){
            map.put("type", "error");
            map.put("msg", "用户删除失败，请联系管理员！");
            return map;
        }
        map.put("type", "success");
        map.put("msg", "用户删除成功！");
        return map;
    }

    /**
     * 上传图片
     * @param photo
     * @param request
     * @return
     */
    @RequestMapping(value="/upload_photo",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadPhoto(@RequestParam(name = "photo",required = false) MultipartFile photo, HttpServletRequest request){
        Map<String, String> map = new HashMap<String, String>();
        if(photo == null){
            map.put("type", "error");
            map.put("msg", "选择要上传的文件！");
            return map;
        }
        if(photo.getSize() > 1024*1024*1024){
            map.put("type", "error");
            map.put("msg", "文件大小不能超过10M！");
            return map;
        }
        //获取文件后缀
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".")+1,photo.getOriginalFilename().length());
        if(!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())){
            map.put("type", "error");
            map.put("msg", "请选择jpg,jpeg,gif,png格式的图片！");
            return map;
        }
        String savePath = request.getSession().getServletContext().getRealPath("/") + "/resources/upload/";
        File savePathFile = new File(savePath);
        if(!savePathFile.exists()){
            //若不存在改目录，则创建目录
            savePathFile.mkdir();
        }
        String filename = new Date().getTime()+"."+suffix;
        try {
            //将文件保存至指定目录
            photo.transferTo(new File(savePath+filename));
        }catch (Exception e) {
            // TODO Auto-generated catch block
            map.put("type", "error");
            map.put("msg", "保存文件异常！");
            e.printStackTrace();
            return map;
        }
        map.put("type", "success");
        map.put("msg", "用户删除成功！");
        map.put("filepath",request.getContextPath() + "/resources/upload/" + filename );
        return map;
    }
    /**
     * 修改密码页面
     * @param model
     * @return
     */
    @RequestMapping(value="/editPassword",method=RequestMethod.GET)
    public ModelAndView editPassword(ModelAndView model){
        model.setViewName("user/editPassword");
        return model;
    }

    @RequestMapping(value="/editPassword",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> editPasswordAct(String newpassword,String oldpassword,HttpServletRequest request){
        Map<String, String> ret = new HashMap<String, String>();
        if(StringUtils.isEmpty(newpassword)){
            ret.put("type", "error");
            ret.put("msg", "请填写新密码！");
            return ret;
        }
        User user = (User)request.getSession().getAttribute("admin");
        if(!user.getPassword().equals(oldpassword)){
            ret.put("type", "error");
            ret.put("msg", "原密码错误！");
            return ret;
        }
        user.setPassword(newpassword);
        if(userService.editPassword(user) <= 0){
            ret.put("type", "error");
            ret.put("msg", "密码修改失败，请联系管理员！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "密码修改成功！");
        logService.add("用户名为{"+user.getUsername()+"}，的用户成功修改密码!");
        return ret;
    }
    /**
     * 判断该用户名是否存在
     * @param username
     * @param id
     * @return
     */
    private boolean isExist(String username,Long id){
        User user = userService.findUserByName(username);
        if(user == null)return false;
        if(user.getId().longValue() == id.longValue())return false;//longValue()是Long类的一个方法，用来得到Long类中的数值；也就是将包装类中的数据拆箱成基本数据类型。
        return true;
    }

}
